package handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import util.PageVO;
import biz.SystemBiz;
import entity.City;
import entity.Menu;
import entity.Province;
import entity.Role;
import entity.Syslog;
import entity.User;
import entity.Userinfo;


@Controller
public class SystemHandler {
	@Autowired
	private SystemBiz systemBiz;

	@RequestMapping("sys_getMenu.do")
	@ResponseBody
	public Object getMenu(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("LoginUser");
		List<Menu> menus = systemBiz.getMenus(user);
		List<Map<Object, Object>> root = new ArrayList<Map<Object, Object>>();
		for (Menu menu : menus) {
			root.add(fillMenu(menu, request.getContextPath()));
		}

		return root;
	}

	@RequestMapping("user_login.do")
	@ResponseBody
	public Object login(HttpServletRequest req, String userName, String password) {
		User user = systemBiz.findUser(userName,0);
		Map<String, Object> json = new HashMap<String, Object>();
		
			if (user == null) {
				// 返回到客户端这个格式{"success":false,"message":"登录名不存在"}
				json.put("success", false);
				json.put("message", "登录名不存在");
			} else if (user.getStatus()==0) {
				json.put("success", false);
				json.put("message", "对不起，此帐号以被管理员停封！");
			} else if (user.getStatus()==2) {
				json.put("success", false);
				json.put("message", "对不起，请耐心等待管理员审核！");
			} else if (!user.getPwd().equals(password)) {
				json.put("success", false);
				json.put("message", "密码输入错误,请重新输入");
			} else {
				json.put("success", true);
				String loginUserName=user.getUserinfo().getName()==null?user.getUname():user.getUserinfo().getName();
				json.put("message", "登录成功,欢迎" + loginUserName + "访问办公自动化管理系统!");
				json.put("userName", loginUserName);
				json.put("passWord", password);
				json.put("userId", user.getId());
				json.put("userRole", user.getRole().getRoleName());
				json.put("roleId", user.getRole().getId());
				
				req.getSession().setAttribute("LoginUser", user);
				req.getSession().setAttribute("LoginUserName", loginUserName);
				req.getSession().setAttribute("UserRole", user.getRole().getRoleName());
			}
			Syslog syslog=new Syslog("用户登录");
			syslog.setUser(user);
			syslog.setIp(req.getRemoteAddr());
			syslog.setValue("userName="+userName+",passWord="+password+",message="+json.get("message"));
			syslog.setLogTime(new Date());
			systemBiz.addLog(syslog);
		return json;
	}

	@RequestMapping("user_logout.do")
	public String logout(HttpSession session) {
		session.removeAttribute("LoginUser");
		session.removeAttribute("UserRole");
		return "redirect:/index.jsp";
	}
	
	@RequestMapping("user_exist.do")
	@ResponseBody
	public Object userExist(String userName,int userId) {
		if (systemBiz.findUser(userName,userId)!=null) {
			return 1;
		}else{
			return 0;
		}
	}
	
	@RequestMapping("user_del.do")
	@ResponseBody
	public Object delUser(int userId) {
		if (systemBiz.delUser(userId)) {
			return 1;
		}else{
			return 0;
		}
		
	}
	
	@RequestMapping("user_query.do")
	@ResponseBody
	public Object userQuery(HttpSession session,User user,int page,int rows) {
		User loginUser = (User) session.getAttribute("LoginUser");
		Map<String, Object> json=new HashMap<String, Object>();
		PageVO<User> users = systemBiz.listUsersByPage(user,loginUser.getRole(), page, rows);
		json.put("total",users.getTotalCount());
		List<Map<String, Object>> pageData=new ArrayList<Map<String,Object>>();
		for (User u : users.getResultList()) {
			Map<String, Object> userVO=new HashMap<String, Object>();
			userVO.put("id", u.getId());
			userVO.put("roleId", u.getRole().getId());
			userVO.put("roleName", u.getRole().getRoleName());
			userVO.put("uname", u.getUname());
			userVO.put("pwd", u.getPwd());
			userVO.put("name", u.getUserinfo()==null?"匿名":u.getUserinfo().getName());
			userVO.put("sex", u.getUserinfo()==null?"保密":u.getUserinfo().getSex());
			userVO.put("birthday", u.getUserinfo()==null?"保密":u.getUserinfo().getBirthday());
			userVO.put("status", u.getStatus());
			userVO.put("provinceId", u.getUserinfo().getProvince()==null?0:u.getUserinfo().getProvince().getId());
			userVO.put("cityId", u.getUserinfo().getCity()==null?0:u.getUserinfo().getCity().getId());
			userVO.put("tel", u.getUserinfo().getTel());
			userVO.put("mobile", u.getUserinfo().getMobile());
			userVO.put("address", u.getUserinfo().getAddress());
			userVO.put("qq", u.getUserinfo().getQq());
			userVO.put("email", u.getUserinfo().getEmail());
			userVO.put("weChat", u.getUserinfo().getWeChat());
			pageData.add(userVO);
		}
		json.put("rows", pageData);
		return json;
	}
	
	@RequestMapping("role_list.do")
	@ResponseBody
	public Object listRoles(HttpSession session) {
		User loginUser = (User) session.getAttribute("LoginUser");
		List<Map<String, Object>> json = new ArrayList<Map<String, Object>>();
		List<Role> roles = systemBiz.listRoles(loginUser.getRole().getId());
		for (Role role : roles) {
			Map<String, Object> r = new HashMap<String, Object>();
			r.put("value",role.getId());
			r.put("text", role.getRoleName());
			json.add(r);
		}
		return json;
	}
	
	@RequestMapping("user_getLogin.do")
	@ResponseBody
	public Object getLoginUser(HttpSession session) {
		User loginUser = (User) session.getAttribute("LoginUser");
		User u = systemBiz.getUserById(loginUser.getId());
		Map<String, Object> userVO=new HashMap<String, Object>();
		userVO.put("id", u.getId());
		userVO.put("roleId", u.getRole().getId());
		userVO.put("roleName", u.getRole().getRoleName());
		userVO.put("uname", u.getUname());
		userVO.put("pwd", u.getPwd());
		userVO.put("name", u.getUserinfo()==null?"匿名":u.getUserinfo().getName());
		userVO.put("sex", u.getUserinfo()==null?"保密":u.getUserinfo().getSex());
		userVO.put("birthday", u.getUserinfo()==null?"保密":u.getUserinfo().getBirthday());
		userVO.put("status", u.getStatus());
		userVO.put("provinceId", u.getUserinfo().getProvince()==null?0:u.getUserinfo().getProvince().getId());
		userVO.put("cityId", u.getUserinfo().getCity()==null?0:u.getUserinfo().getCity().getId());
		userVO.put("tel", u.getUserinfo().getTel());
		userVO.put("mobile", u.getUserinfo().getMobile());
		userVO.put("address", u.getUserinfo().getAddress());
		userVO.put("qq", u.getUserinfo().getQq());
		userVO.put("email", u.getUserinfo().getEmail());
		userVO.put("weChat", u.getUserinfo().getWeChat());
		return userVO;
	}
	
	@RequestMapping("user_saveorupdate.do")
	@ResponseBody
	public int saveOrUpdateUser(String action,User user,Userinfo info,int roleId,int provinceId,int cityId) {
		if(provinceId>0){
			info.setProvince(new Province(provinceId));
		}
		if(cityId>0){
			info.setCity(new City(cityId));
		}
		user.setUserinfo(info);
		user.setRole(new Role(roleId));
		info.setUser(user);
		if("update".equals(action)){
			if(systemBiz.updateUser(user)){
				return 1;
			}else{
				return 0;
			}
		}else if("add".equals(action)){
			user.setId(null);
			info.setId(null);
			return systemBiz.addUser(user);
		}else{
			return 0;
		}
	}
	@RequestMapping("user_updatestatus.do")
	@ResponseBody
	public int updateUserStatus(@RequestParam("ids[]")int[] ids,int status) {
		if (systemBiz.updateUserStatus(ids,status)) {
			return 1;
		} else {
			return 0;
		}
	}
	

	private Map<Object, Object> fillMenu(Menu menu, String contextPath) {
		Map<Object, Object> jm = new HashMap<Object, Object>();
		jm.put("id", menu.getId());
		jm.put("text", menu.getText());
		if (menu.getSubMenus() != null && menu.getSubMenus().size() > 0) {
			jm.put("state", "closed");
			jm.put("iconCls", "icon-add");
			List<Map<Object, Object>> ja = new ArrayList<Map<Object, Object>>();
			for (Menu subMenu : menu.getSubMenus()) {
				ja.add(fillMenu(subMenu, contextPath));
			}
			jm.put("children", ja);
		} else {
			jm.put("attributes", contextPath + menu.getUrl());
		}
		return jm;
	}
}
